<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-button type="primary" @click="showAdd()">添加分类</el-button>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="cat_id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          prop="cat_name"
          label="分类名称"
          colspan="1"
          rowspan="1"
        >
        </el-table-column>
        <el-table-column prop="name" label="是否有效" colspan="1" rowspan="1">
          <span class="el-icon-success" style="color: lightgreen"></span>
        </el-table-column>
        <el-table-column prop="address" label="排序" colspan="1" rowspan="1">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag
              size="mini"
              type="success"
              v-else-if="scope.row.cat_level === 1"
              >二级</el-tag
            >
            <el-tag size="mini" type="warning" v-else>三级</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>
      <el-dialog
        title="添加分类"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="closeFn()"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="ruleForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <div class="block">
              <el-cascader
                v-model="selectedKeys"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange()"
                clearable
              ></el-cascader>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="btn()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    this.getTree()
    this.getCateList()
  },
  data() {
    return {
      tableData: [],
      cateList: [],
      total: 0,
      currentPage4: 1,
      pageSize: 5,
      dialogVisible: false,
      ruleForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        leaf: 'cat_level',
        expandTrigger: 'hover',
        checkStrictly: true,
      },
      selectedKeys: [],
      rules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur',
          },
        ],
        region: [{ message: '请选择', trigger: 'change' }],
      },
    }
  },
  methods: {
    btn() {
      console.log(this.ruleForm)
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return //校验失败，不提交
        }
        const { data: res } = await this.$http.post(
          '/categories',
          this.ruleForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        this.getTree() //刷新分类列表
        this.dialogVisible = false //关闭对话框
      })
    },
    closeFn() {
      this.$refs.ruleForm.resetFields()
      this.selectedKeys = []
      this.ruleForm.cat_pid = 0
      this.ruleForm.cat_level = 0
    },
    onSubmit() {
      console.log('submit!')
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.getTree()
    },
    handleCurrentChange(val) {
      this.currentPage4 = val
      this.getTree()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    showAdd() {
      this.getCateList()
      this.dialogVisible = true
    },
    handleChange() {
      console.log(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        this.ruleForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.ruleForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.ruleForm.cat_pid = 0
        this.ruleForm.cat_level = 0
      }
    },
    async getTree() {
      let res = await this.$http({
        url: '/categories',
        params: {
          type: 3,
          pagenum: this.currentPage4,
          pagesize: this.pageSize,
        },
      })
      this.tableData = res.data.data.result
      // console.log(this.tableData)
      this.total = res.data.data.total
    },
    async getCateList() {
      const { data: res } = await this.$http.get('/categories', {
        params: { type: 2 },
      })
      this.cateList = res.data
      console.log(this.cateList)
    },
  },
}
</script>

<style lang="less" scoped></style>
